const DB = require('../../../../utils/db')
const JwtUtil = require('../../../../utils/jwt')
/**
 * GET, 参数friendid
 * 搜索好友
 */

module.exports = async (ctx) => {
  // 获取token
  let token = ctx.request.header.authorization
  let jwt = new JwtUtil(token)
  // 用token获取到userid
  let userid = jwt.verifyToken()
  const friendInformation = await DB.query(
    `select * from user where userid='${ctx.request.query.friendid}';`
  )
  const hasFriend = await DB.query(
    `select * from user_friend where (userid='${userid}' and friendid='${ctx.request.query.friendid}') or (userid='${ctx.request.query.friendid}' and friendid='${userid}')`
  )
  if (hasFriend.length === 2) {
    // 已经是好友了
    ctx.body = {
      code: 0,
      data: { ...friendInformation[0], isFriend: true  },
    }
  }else{
    // 不是好友,那么查询申请信息
    const applyres = await DB.query(
      `select applyStatus from user_apply where applicantid='${userid}' and respondentid='${ctx.request.query.friendid}'`
    )
      ctx.body = {
        code: 0,
        data: { ...friendInformation[0], isFriend: false, ...applyres[0]},
      }
  }
}
